package com.example.gybicycle.common.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;


public class ImageUtil {
    public static void  upImg() throws IOException {
        File file=new File("C:\\Users\\Administrator.SY-202304151755\\Pictures\\supplier\\3-18-1.jpg");
        File destfile=new File("D:\\3-18-1.jpg");
        BufferedImage read = ImageIO.read(file);
        Graphics2D graphics = read.createGraphics();
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        int width=(int) (read.getWidth());
        int hight=read.getHeight();
        graphics.setStroke(new BasicStroke(5.f));
        int ww=width/8,hh=hight/8;
        graphics.drawLine(width/2,hight/2-ww,width/2,hight/2+ww);
        graphics.drawLine(width/2-hh,hight/2,width/2+hh,hight/2);
        String fileName = file.getName();
        String formatName = fileName.substring(fileName.lastIndexOf(".") + 1);
        ImageIO.write(read,formatName,destfile);
    }
    /**
     * 对图片进行原比例无损压缩,压缩后覆盖原图片
     *
     * @param path
     */
    private static void doWithPhoto(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        int dotIndex = file.getName().lastIndexOf('.');
        String extension = "";
        if (dotIndex != -1) {
            extension = file.getName().substring(dotIndex + 1);
        }
        BufferedImage image = null;
//        FileOutputStream os = null;
        try {
            image = ImageIO.read(file);
            int width = image.getWidth();
            int height = image.getHeight();
            BufferedImage bfImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            bfImage.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
//            os = new FileOutputStream(path);
            ImageIO.write(image,  extension , new File(path));
            image.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static void doWithPhoto(File file) {
        BufferedImage image = null;
        int dotIndex = file.getName().lastIndexOf('.');
        String extension = "";
        if (dotIndex != -1) {
            extension = file.getName().substring(dotIndex + 1);
        }
        try {
            image = ImageIO.read(file);
            int width = image.getWidth();
            int height = image.getHeight();
            BufferedImage bfImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            bfImage.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
//            os = new FileOutputStream(path);
            ImageIO.write(image,  extension ,file);
            image.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void compressImage(String path,int targetSizeKB) throws IOException {
        File file=new File(path);
        long len=file.length();
        double size=(double) file.length()/1024;
        if(size<=100)
            return;
        String outPath=path;
        BufferedImage image = ImageIO.read(file);
        Image compressedImage = compressImage(image, targetSizeKB,len);
        ImageIO.write((BufferedImage) compressedImage, "jpg", new File(outPath));
    }
    public static void compressImage(File file,int targetSizeKB) throws IOException {
        long len=file.length();
        double size=(double) file.length()/1024;
        if(size<=100)
            return;
        BufferedImage image = ImageIO.read(file);
        Image compressedImage = compressImage(image, targetSizeKB,len);
        ImageIO.write((BufferedImage) compressedImage, "jpg", file);
    }
    public static Image compressImage(BufferedImage image, int targetSizeKB,long filelen) {
        // 计算目标图片的尺寸
        long targetSizeBytes = targetSizeKB * 1024;
//        long originalSizeBytes = getImageSize(image);
        double compressionRatio = (double) targetSizeBytes / filelen;
        int targetWidth = (int) (image.getWidth() * Math.sqrt(compressionRatio));
        int targetHeight = (int) (image.getHeight() * Math.sqrt(compressionRatio));
        // 使用ImageIO进行压缩
        BufferedImage compressedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
        compressedImage.getGraphics().drawImage(image.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH), 0, 0, null);
        return compressedImage;
    }


  /*  public static long getImageSize(BufferedImage image) {
        File tempFile;
        try {
            tempFile = File.createTempFile("temp", ".tmp");
            ImageIO.write(image, "jpg", tempFile);
            long size = tempFile.length();
            tempFile.delete();
            return size;
        } catch (IOException ex) {
            ex.printStackTrace();
            return 0;
        }
    }*/
    public static  void rotate( File file){
        try {
            int dotIndex = file.getName().lastIndexOf('.');
            String extension = "";
            if (dotIndex != -1) {
                extension = file.getName().substring(dotIndex + 1);
            }
            BufferedImage image=ImageIO.read(file);
            int wdith=image.getWidth();
            int height=image.getHeight();
            int rw=height,rh=wdith;
             BufferedImage rimg=new BufferedImage(rw,rh,image.getType());
             for(int x=0;x<wdith;x++){
                 for(int y=0;y<height;y++){
                     int rx=y;
                     int ry=wdith-x-1;
                     int rgb=image.getRGB(x,y);
                     rimg.setRGB(rx,ry,rgb);
                 }
             }
             ImageIO.write(rimg,extension,file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static  void rotate( String path){
        try {
            File file=new File(path);
            int dotIndex = file.getName().lastIndexOf('.');
            String extension = "";
            if (dotIndex != -1) {
                extension = file.getName().substring(dotIndex + 1);
            }
            BufferedImage image=ImageIO.read(file);
            int wdith=image.getWidth();
            int height=image.getHeight();
            int rw=height,rh=wdith;
            BufferedImage rimg=new BufferedImage(rw,rh,image.getType());
            for(int x=0;x<wdith;x++){
                for(int y=0;y<height;y++){
                    int rx=y;
                    int ry=wdith-x-1;
                    int rgb=image.getRGB(x,y);
                    rimg.setRGB(rx,ry,rgb);
                }
            }
            ImageIO.write(rimg,extension,new File(path));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static  void shuiyin(String path,String lat) throws IOException {
         ImageUtil.shuiyin(new File(path),lat);
    }

    public static  void shuiyin(File file,String lat) throws IOException {
       String text= DataUtil.toString(new Date(),"yyyy.MM.dd") ;
       if(lat!=null  && lat.length()>0)
           text=text+" "+lat;
        int dotIndex = file.getName().lastIndexOf('.');
        String extension = "";
        if (dotIndex != -1) {
            extension = file.getName().substring(dotIndex + 1);
        }
        BufferedImage sourceImage = ImageIO.read(file);

        // 创建图形上下文
        Graphics2D g2d = (Graphics2D) sourceImage.getGraphics();

        // 获取图片的宽度和高度
        int width = sourceImage.getWidth();
        int height = sourceImage.getHeight();
        int size=width/100;
        if(size==0)
            size=1;
        // 设置水印文字颜色和字体等属性
        AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
        g2d.setComposite(alphaChannel);
        g2d.setColor(Color.BLUE);
        g2d.setFont(new Font("宋体", Font.BOLD, size*5));
        FontMetrics metrics=g2d.getFontMetrics();
        int textWidth=metrics.stringWidth(text)+10;
        // 在图片上绘制水印文字
        g2d.drawString(text, width - textWidth, height - 20);

        // 释放图形上下文资源
        g2d.dispose();

        // 输出带有水印的图片
        ImageIO.write(sourceImage, extension, file);
    }

    public static void main(String[] args) {
        try {
//            compressImage("D:\\create\\bike\\bg.png",300);
//            doWithPhoto("D:\\create\\bike\\bg.png");
//            String id="MEMBER202406210001";
//            System.out.println(id.substring(6));
//            String satrt="2024-07-04 11:51:43";
//            Date date=DataUtil.toDate(satrt,"yyyy-MM-dd HH:mm:ss");
//            String dre=DataUtil.Duration(date,new Date());
            /*List<String> xx=Arrays.asList("2024.05.14","2024.06.03","2024.05.19");
            List<String> re=xx.stream().sorted(Comparator.comparing(Objects::toString)).collect(Collectors.toList());
            for (String str:re) {
                System.out.println(str);
            }*/

//            PatrolPoints points=new PatrolPoints();
//            points.setId(1);
//            points.setName("测试");
//            String json= JSON.toJSONString(points);
////            createQRcode()D:\create
////            QRCodeGenerator.createQRcode("https://fanyi.baidu.com/?","D:\\create\\","test.jpg");
//            QRCodeGenerator.createQRcode(json,"测试","D:\\create\\","test1.jpg");
////            String path="D:\\create\\20240514222.png";
//            String path="D:\\create\\20240514220.jpg";
//            File file=new File(path);
//            QRCodeUtil.createImg("pages/Merchant/index?merchantId=142","跳转地址","D:\\create\\test2.jpg");
//            QRCodeGenerator.createQRcode(" pages/Merchant/index?merchantId=142","D:\\create\\","test2.jpg");
//
//            System.out.println("success");

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
